<template>
    <el-tabs v-model="formData.mediaType" size="small">
        <el-tab-pane v-if="$btnAuth('projectListInner')" label="梯内屏" :name="1"></el-tab-pane>
        <el-tab-pane v-if="$btnAuth('projectListOut')" label="梯外屏" :name="2"></el-tab-pane>
    </el-tabs>
    <XcForm ref="xcFormRef" class="pinmei-form" :form-data="formData" :columns="formColumns">
        <template #planName-prefix>
            <div class="label">
                <el-icon :size="16">
                    <Search />
                </el-icon>
            </div>
        </template>
        <template #city-prefix> 投放城市 </template>
        <template #planSource-prefix> 方案来源 </template>
        <template #planStatusList-prefix> 方案状态 </template>
        <template #orderId-prefix>
            <div class="label">
                <el-icon :size="16">
                    <Search />
                </el-icon>
            </div>
        </template>
    </XcForm>

    <div v-loading="tableLoading">
        <section class="btn-group cancel-list">
            <div class="left-btns">
                <el-button :loading="exportLoading" @click="handleExportPlan">
                    导出全部方案
                </el-button>
                <el-button type="primary" class="m-r-15" @click="onCreatProgram">
                    新建方案
                </el-button>
                <el-dropdown popper-class="button-dropdown" trigger="click" class="el-dropdown-base m-r-15">
                    <el-button type="primary"> 批量操作<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item @click="batchExportPoint"> 批量导出点位 </el-dropdown-item>
                            <el-dropdown-item @click="batchCancelPoint"> 批量取消方案 </el-dropdown-item>
                            <!-- //梯外推送方案 2.2.5 取消批量操作 -->
                            <!-- <el-dropdown-item @click="batchExportRealSKTable">批量导出实际上刊点位表</el-dropdown-item>
                            <el-dropdown-item @click="batchExportKanbaoPhoto">批量导出刊播照片</el-dropdown-item> -->
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <el-button class="query-point" type="primary" @click="showSearchPoint">查询空位</el-button>


                <!-- <el-dropdown v-if="$btnAuth('uploadPht')" popper-class="button-dropdown" trigger="click"
                    class="el-dropdown-base m-r-15">
                    <el-button type="primary" > 照片上传<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item @click="openPerUploadPhtDrawer">单个上传</el-dropdown-item>
                            <el-dropdown-item @click="openBatchUploadPhtDrawer">批量上传</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown> -->
            </div>

            <div class="cancel-switch">
                <span>显示已取消方案</span>
                <el-switch v-model="showCancelList" @change="getCancelListAction" />
            </div>
        </section>
        <XcTable :key="keyNum" id="xc-table" class="custom-table-operate" :data="tableData" :columns="tableColumns"
            :is-selectable="true" :select-enable="(row: any, rowIndex: any) => !showCancelList"
            @selection-change="selectedChange">
            <template #planStatus="{ row }">
                <XcTag size="medium" :text="row && row.planStatusName" :type="ProgramButtonType[row && row.planStatus]">
                </XcTag>
            </template>
            <template #pointNumLimit="{ row }">
                {{ row.pointNumLimit === 0 ? '无限制' : row.pointNumLimit }}
            </template>
            <template #planSourceName="{ row }">
                <el-button v-if="isFromZt(row.planSource)" type="text" @click="handleShowSourceInfo(row)">
                    {{ row.planSourceName }}
                </el-button>
                <template v-else>
                    {{ row.planSourceName }}
                </template>
            </template>
            <template #creativeName="{ row }">
                <template v-if="isFromZt(row.planSource)">
                    <span class="grayColor">--</span>
                </template>
                <el-button v-else-if="row.creativeId" type="text" @click="handleViweIdea(row)">
                    {{ row.creativeName }}
                </el-button>
                <template v-else>
                    <span class="grayColor">暂未关联创意</span>
                </template>
            </template>
            <template #skReportStatus="{ row }">
                {{ ReportStatus[row.skReportStatus] }}
            </template>
            <template #xkReportStatus="{ row }">
                {{ ReportStatus[row.xkReportStatus] }}
            </template>
            <template #mediaType="{ row }">
                <!-- {{ row.position }}  todo -->
                {{ row.mediaType }}
                {{ mediaType[row.mediaType] }}
            </template>
            <template #action="{ row }">
                <el-button
                    v-if="!isFromZt(row.planSource) && row.planStatus === ProgramType.LOCK && !isAfter(row.beginTime) && !showCancelList"
                    type="text" @click="handleShowEditIdea(row, '关联创意')" class="create-btn">
                    关联创意
                </el-button>
                <!-- <el-button
                v-if="
                    (row.planStatus === ProgramType.DRAFT || row.planStatus === ProgramType.LOCK) &&
                    !isFromZt(row.planSource) &&
                    !showCancelList
                "
                type="text"
                @click="handleEditPoint(row)"
            >
                选择点位
            </el-button> -->
                <el-button v-if="showCancelList" type="text" @click="handleRecover(row)"> 恢复方案 </el-button>
                <el-dropdown v-if="!showCancelList">
                    <span class="el-dropdown-link">
                        点位
                        <el-icon class="el-icon--right">
                            <arrow-down />
                        </el-icon>
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item v-if="!isFromZt(row.planSource) && row.planStatus !== ProgramType.DRAFT"
                                @click="handlePoint(row)"> 快速调整点位 </el-dropdown-item>
                            <el-dropdown-item @click="handleShowKicked(row)"> 查看被踢点位 </el-dropdown-item>
                            <el-dropdown-item @click="handleExportPoint(row)"> 导出点位 </el-dropdown-item>
                            <el-dropdown-item v-if="(row.planStatus === ProgramType.DRAFT || row.planStatus === ProgramType.LOCK) &&
                                !isFromZt(row.planSource) &&
                                !isAfter(row.beginTime) &&
                                !showCancelList
                                " @click="handleEditPoint(row)">
                                选择点位
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <el-dropdown
                    v-if="row.planStatus === ProgramType.ENSURE && !isFromZt(row.planSource) && formData.mediaType === 1">
                    <span class="el-dropdown-link">
                        刊播报告
                        <el-icon class="el-icon--right">
                            <arrow-down />
                        </el-icon>
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item @click="makeReport(row)"> 制作报告 </el-dropdown-item>
                            <el-dropdown-item @click="viweReport(row)"> 查看报告 </el-dropdown-item>
                            <el-dropdown-item @click="onDownloadReport(row)"> 下载报告
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <el-dropdown v-if="!isFromZt(row.planSource)">
                    <span class="el-dropdown-link">
                        更多
                        <el-icon class="el-icon--right">
                            <arrow-down />
                        </el-icon>
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item @click="handleShowEdit(row)"> 编辑方案信息 </el-dropdown-item>
                            <el-dropdown-item v-if="row.planStatus === ProgramType.ENSURE && !isAfter(row.endTime)"
                                @click="handleShowEditIdea(row, '更换创意')">
                                更换创意
                            </el-dropdown-item>
                            <el-dropdown-item
                                v-if="!(isAfter(row.beginTime) && row.planStatus === ProgramType.ENSURE) && !showCancelList"
                                @click="handleCancelPlan(row)">
                                取消方案
                            </el-dropdown-item>
                            <el-dropdown-item v-if="isShowDisassmbly(row) && !showCancelList"
                                @click="handleDisassemblyPlan(row)"> 方案拆解 </el-dropdown-item>
                            <el-dropdown-item v-if="isRepelStatus(row) && !showCancelList" @click="handleRepelList(row)">
                                方案排斥 </el-dropdown-item>
                            <el-dropdown-item @click="onCopyPlan(row)"> 复制方案 </el-dropdown-item>
                            <el-dropdown-item @click="exportRealSKTable(row)"> 导出实际上刊点位表</el-dropdown-item>
                            <el-dropdown-item @click="exportKanbaoPhoto(row)"> 导出刊播照片 </el-dropdown-item>
                            <el-dropdown-item @click="exportKanbaoReport(row)"> 导出数字刊播报告</el-dropdown-item>
                            <el-dropdown-item v-if="$btnAuth('viewSphoto')" @click="viewPhoto(row, '001')"> 查看上刊照片
                            </el-dropdown-item>
                            <el-dropdown-item v-if="$btnAuth('viewXphoto')" @click="viewPhoto(row, '002')"> 查看下刊照片
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </template>
        </XcTable>

        <Pagination :page-no="pageInfo.pageNum" :page-size="pageInfo.pageSize" :total="pageInfo.total"
            @changePage="changePage" @changePageSize="changePageSize"></Pagination>
    </div>
    <ExportPointDialog v-if="showExportPoint" v-model="showExportPoint" :plan-detail="currentPlan" />
    <HandelPointDialog v-model="showHandelPoint" title="调整选点" :plan-detail="currentPlan" @success="getList" />
    <EditPlanDrawer v-if="showEdit" v-model="showEdit" :plan-detail="currentPlan" @success="getList" />
    <GetKickedDrawer v-if="showKicked" v-model="showKicked" :plan-detail="currentPlan" @success="getList" />
    <EditIdeaDrawer v-if="showEditIdea" v-model="showEditIdea" :title="currentPlan.title" :plan-detail="currentPlan"
        @success="getList" />
    <EditPointDrawer v-if="showEditPoint" v-model="showEditPoint" :plan-detail="currentPlan" @success="getList" />
    <ViewIdeasDrawer v-model="showViewIdeas" :ideas-id="ideasId" />
    <SignDailog v-if="showSignDailog" :model-value="showSignDailog" @handleClose="handleCloseSignDailog" />
    <Disassembly ref="disassembly" :row="curRow" @get-list="getList" />
    <CancelProgramDialog v-model="showCancelDialog" @cancelSubmit="getList" />
    <BatchPointDialog v-model="showBatchPointlDialog" :select-data="multipleSelection" @batchSubmit="getList" />

    <KanboPhotoDialog v-model="showKanboPhotolDialog" :plan-data="curOptPlanRow" />
    <KanboReportDialog v-model="showKanboReportlDialog" :show-data="showClipboard" />

    <SearchPointDrawer v-model="showSearchPointDraw" :media-type="formData.mediaType" @batchSubmit="getList" />
    <RepelProjectDrawer v-model="showRepelProjectDraw" :select-row="selectRow" @success="getList" />
    <perUploadPhtDrawer :mediaType="formData.mediaType" v-model="showPerUploadPhtDraw" />
</template>

<script setup lang="ts">
import { computed, reactive, ref, shallowRef, provide, watch, defineAsyncComponent } from 'vue';
import XcForm from '@x-tech/fe-pc-components/src/components/XcForm/index.vue';
import XcTag from '@x-tech/fe-pc-components/src/components/XcTag/index.vue';
import XcTable from '@x-tech/fe-pc-components/src/components/XcTableTemplate/XcTable.vue';
import useSearchForm from './hooks/useSearchForm.tsx';
import useTableSetting from '@/hooks/useTableSetting.ts';
import { exportFormBlob, downLoadCommon, isAfter, isBefore, downloadFile } from '@/utils/common.ts';
import Pagination from '@/components/common/Pagination.vue';
import usePagInfo from './hooks/usePagInfo.ts';
import { getPlanList, cancelPlan, exportPlan, getZtinfo, getRecoverList, getJoinSignApproval } from '@/api/plan.ts';
import { downloadReport } from '@/api/carryBroadcast.ts';
import { ProgramButtonType, ProgramType } from './programType.ts';
import { useRouter, useRoute } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useStore } from 'vuex';
import type { FormInstance } from 'element-plus';
import dayjs from 'dayjs';
import { writeDataToClipboard, copyTextToClipboard, exportFile } from '@/utils/common';
import { exportKanBoReport, exportRealPointExcel } from '@/api/point';
import { $btnAuth } from '@/utils/common';

const keyNum = ref(0);
const ExportPointDialog = defineAsyncComponent(() => import('./components/exportPointDialog.vue'));
const HandelPointDialog = defineAsyncComponent(() => import('./components/handelPointDialog.vue'));
const EditPlanDrawer = defineAsyncComponent(() => import('./components/editPlanDrawer.vue'));
const GetKickedDrawer = defineAsyncComponent(() => import('./components/getKickedDrawer.vue'));
const EditIdeaDrawer = defineAsyncComponent(() => import('./components/editIdeaDrawer.vue'));
const EditPointDrawer = defineAsyncComponent(() => import('./components/editPointDrawer.vue'));
const ViewIdeasDrawer = defineAsyncComponent(() => import('./components/viewIdeas.vue'));
const Disassembly = defineAsyncComponent(() => import('./components/disassembly.vue'));
const SignDailog = defineAsyncComponent(() => import('./components/signDailog.vue'));
const CancelProgramDialog = defineAsyncComponent(() => import('./components/cancelProgramDialog.vue'));
const BatchPointDialog = defineAsyncComponent(() => import('./components/batchPointDialog.vue'));
const KanboPhotoDialog = defineAsyncComponent(() => import('./components/kanboPhotoExportDialog.vue'));
const KanboReportDialog = defineAsyncComponent(() => import('./components/kanboReportExportDialog.vue'));

const SearchPointDrawer = defineAsyncComponent(() => import('./components/searchPoint.vue'));
const RepelProjectDrawer = defineAsyncComponent(() => import('./components/repelProjectDrawer.vue'));
const perUploadPhtDrawer = defineAsyncComponent(() => import('./components/perUploadPhtDrawer.vue'));

const store = useStore();
const xcFormRef = ref<FormInstance>();
const exportLoading = ref(false);
const showExportPoint = ref(false);
const showHandelPoint = ref(false);
const showEdit = ref(false);
const showEditIdea = ref(false);
const showKicked = ref(false);
const showEditPoint = ref(false);
const showViewIdeas = ref(false);
const showSignDailog = ref(false);
const ideasId = ref(null);
const currentPlan = ref({});
const tableLoading = ref(false);
const showCancelDialog = ref(false);
const showBatchPointlDialog = ref(false);
const showKanboPhotolDialog = ref(false);
const showKanboReportlDialog = ref(false);

const showSearchPointDraw = ref(false);
const showRepelProjectDraw = ref(false);
const showPerUploadPhtDraw = ref(false);


const disassembly = ref();
// const showCancelList = ref(false);
let selectRow = reactive({});
const tableData = shallowRef([]);
const curRow = ref({});
const ReportStatus = reactive({
    '0': '不需要',
    '1': '未制作',
    '2': '已制作',
});

const mediaType = reactive({
    '0': '未知',
    '1': '梯内',
    '2': '梯外',
});

const router = useRouter();

const { pageInfo, changePage, changePageSize } = usePagInfo();
const userInfo: any = computed(() => store.state.userGroup.userInfo);

const getDate = (n: number | string): string | number => {
    const now = new Date(n),
        y = now.getFullYear(),
        m = now.getMonth() + 1,
        d = now.getDate();
    return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
};

const getList = async () => {
    tableLoading.value = true;
    // eslint-disable-next-line no-use-before-define
    if (showCancelList.value) {
        // eslint-disable-next-line no-use-before-define
        formData.planStatusList = '';
    }
    // eslint-disable-next-line no-use-before-define
    try {
        // eslint-disable-next-line no-use-before-define
        const params = { ...formData, ...pageInfo, deleted: showCancelList.value };
        console.log('params:', params);
        const { list = [], total = 0 } = await getPlanList(params);
        console.log('list', list);
        keyNum.value++;
        tableData.value = list.map((item) => ({
            ...item,
            beginTime: dayjs.unix(item.beginTime),
            endTime: dayjs.unix(item.endTime),
            upMan: item.upMan === 0 ? null : item.upMan,
        }));
        pageInfo.total = total;
    } finally {
        tableLoading.value = false;
    }
};

const handleSearch = () => {
    pageInfo.pageNum = 1;
    getList();
};
const handleResetForm = () => {
    xcFormRef.value.refForm.resetFields();
};
const { formData, columns: formColumns, showCancelList } = useSearchForm(handleSearch, handleResetForm);

formData.mediaType = store.state.plan.curMediaType;

const isShowDisassmbly = (row: any): boolean => {
    if (formData.mediaType === 2) {
        return false;
    } // 体外方案直接屏蔽

    const putInPeriod = row.putInPeriod.split('~')[1];
    const time = new Date(new Date(getDate(putInPeriod)).setHours(0, 0, 0, 0)).getTime();
    const today = new Date(new Date().setHours(0, 0, 0, 0)).getTime();
    return (row.planStatus === '001' || row.planStatus === '002' || row.planStatus === '003') && time >= today;
};

watch(
    () => [pageInfo.pageNum, pageInfo.pageSize, formData.mediaType],
    () => {
        // 调用列表
        getList();
        store.commit('plan/setCurMediaType', formData.mediaType);
    }
);

const handleExportPlan = async () => {
    const params = { ...formData, ...pageInfo };

    console.log('param:', params);
    exportLoading.value = true;
    try {
        const { file, fileName } = await exportPlan({ ...params, deleted: showCancelList.value });
        exportFormBlob(file, fileName);
    } finally {
        exportLoading.value = false;
    }
};

const tableColumns = [
    { label: '方案ID', key: 'planId', prop: { width: '150', fixed: 'left' } },
    { label: '方案名称', key: 'planName', prop: { width: '200', fixed: 'left' } },
    { label: '方案状态', key: 'planStatus', render: true, prop: { width: '150'} },
    { label: '投放城市', key: 'cityName', prop: { width: '200' } },
    { label: '行业', key: 'tradeName', prop: { width: '200' } },
    { label: '媒体类型', key: 'mediaTypeName', prop: { width: '200' } },

    { label: '投放周期', key: 'putInPeriod', prop: { width: '250' } },
    { label: '投放规格', key: 'launchSpec', prop: { width: '250' } }, //  屏幕类型 -时长 - 频次
    { label: '销售类型', key: 'saleTypeName', prop: { width: '250' } }, //

    { label: '时长', key: 'secondsName', prop: { width: '200' } },
    { label: '频次', key: 'numbersName', prop: { width: '200' } },
    { label: '屏幕类型', key: 'screenTypeName', prop: { width: '200' } },

    { label: '签约点位', key: 'compactNum', prop: { width: '200' } },
    { label: '调剂点位', key: 'regulateNum', prop: { width: '200' } },
    { label: '点位数上限', key: 'pointNumLimit', render: true, prop: { width: '200' } },

    { label: '已选点位', key: 'selectedPointNum', prop: { width: '200' } },
    { label: '被踢点位', key: 'kickedPointNum', prop: { width: '200' } },
    { label: '关联创意', key: 'creativeName', render: true, prop: { width: '200' } },
    { label: '方案来源', key: 'planSourceName', render: true, prop: { width: '200' } },
    { label: '智投方案名称', key: 'ztPlanName', render: true, prop: { width: '200' } },
    { label: '上刊拍照要求', key: 'photoUpReport', render: true, prop: { width: '200' } },
    { label: '下刊拍照要求', key: 'photoDownReport', render: true, prop: { width: '200' } },

    { label: '签约单', key: 'orderName', prop: { width: '200' } },
    { label: '创建时间', key: 'createTimeStr', prop: { width: '200' } },
    { label: '创建人', key: 'createManName', prop: { width: '200' } },
    { label: '上刊报告', key: 'skReportStatus', render: true, prop: { width: '200' } },
    { label: '下刊报告', key: 'xkReportStatus', render: true, prop: { width: '200' } },
    { label: '更新时间', key: 'updateTimeStr', prop: { width: '200' } },
    { label: '更新人', key: 'upManName', prop: { width: '200' } },
    { label: '操作', key: 'action', render: true, prop: { fixed: 'right', width: '280' } },
];

const handleCancelPlan = async ({ planId }) => {
    await ElMessageBox.confirm('取消后将无法恢复，确认操作吗？', '提示', {
        type: 'warning',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
    });
    await cancelPlan(planId);
    getList();
};
const handleDisassemblyPlan = async (row: any) => {
    curRow.value = row;
    disassembly.value.show();
};
const handlePoint = (current) => {
    currentPlan.value = current;
    showHandelPoint.value = true;
};

const handleExportPoint = (current) => {
    currentPlan.value = current;
    showExportPoint.value = true;
};

const handleShowEdit = (current) => {
    currentPlan.value = current;
    store.commit('plan/setPlanId', '');
    showEdit.value = true;
};
const makeReport = (row) => {
    if (row.skReportStatus === 2 && row.xkReportStatus === 2) {
        ElMessage.error('如需重做报告，先作废对应报告');
    } else if (row.skReportStatus === 1 || row.xkReportStatus === 1) {
        const imgType = row.skReportStatus === 1 ? '001' : '002';
        router.push({
            path: '/delivery/checkScreen',
            query: { planId: row.planId, imgType },
        });
    } else if (row.skReportStatus === 0 && row.xkReportStatus === 0) {
        ElMessage.error('不需要做报告');
    } else {
        ElMessage.error('如需重做报告，先作废对应报告');
    }
};
const viweReport = (row) => {
    if (row.skReportStatus === 2 || row.xkReportStatus === 2) {
        router.push({
            path: '/delivery/viewReport',
            query: { planId: row.planId },
        });
    } else {
        ElMessage.error('无预览的报告');
    }
};
const onDownloadReport = async (row) => {
    if (row.skReportStatus === 2 || row.xkReportStatus === 2) {
        let reportType = null;
        if (row.skReportStatus === 2 && row.xkReportStatus !== 2) {
            reportType = 1;
        } else if (row.skReportStatus !== 2 && row.xkReportStatus === 2) {
            reportType = 2;
        } else if (row.skReportStatus === 2 && row.xkReportStatus === 2) {
            reportType = '';
        }
        const params = { planId: row.planId, reportType };
        const data = await downloadReport(params);
        downLoadCommon(data);
    } else {
        ElMessage.error('无下载的报告');
    }
};
const handleShowEditIdea = (current, title) => {
    currentPlan.value = {
        ...current,
        title,
    };
    store.commit('plan/setPlanId', current.planId);
    if (current.planStatus === ProgramType.LOCK && !current.orderId.startsWith('WBQYD') && userInfo.value.useCrm) {
        showSignDailog.value = true;
    } else {
        showEditIdea.value = true;
    }
};

const handleCloseSignDailog = (type: string) => {
    showSignDailog.value = false;
    if (type) {
        showEditIdea.value = true;
    }
};

const handleViweIdea = (current) => {
    showViewIdeas.value = true;
    ideasId.value = current.creativeId;
};
const handleShowKicked = (current) => {
    currentPlan.value = current;
    showKicked.value = true;
};
const handleEditPoint = (current) => {
    store.commit('plan/setPlanId', current.planId);
    store.commit('plan/setCurMediaType', current.mediaType);

    router.push({
        path: '/delivery/program/create',
        query: { step: 1, planId: current.planId, planStatus: current.planStatus, orderId: current.orderId },
    });
};
const onCopyPlan = (current) => {
    store.commit('plan/setPlanId', current.planId);
    router.push({
        path: '/delivery/program/create',
    });
};
const onCreatProgram = () => {
    store.commit('plan/setPlanId', '');
    router.push({ name: 'CreatProgram' });
};

const isFromZt = (sourceStatus: string) => {
    return sourceStatus === '010' || sourceStatus === 'ZT';
};

const handleShowSourceInfo = async (planInfo: { ztId?: string; ztName?: string }) => {
    const { planId = null } = planInfo;
    const { ztId, ztName } = await getZtinfo({ planId });
    ElMessageBox.alert(
        `
        <section>
            <label style="color:#666666">智投方案ID：</label>${ztId}
        </section>
         <section>
            <label style="color:#666666">智投方案名称：</label>${ztName}
        </section>
    `,
        '生活圈智投方案',
        {
            dangerouslyUseHTMLString: true,
        }
    );
};

// const judgeCancel = () => true;
// const { maxTableHeight } = useTableSetting();

// V2.1.2_点位查询方案排斥需求加入
const multipleSelection = ref([]);
// 提示：请至少勾选一个方案
const showSelectWarn = () => {
    return ElMessageBox.alert('请至少勾选一个方案', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning',
        draggable: true,
        title: '提示',
    }).then(
        () => true,
        () => false
    );
};

// 提示：取消方案，提示满足条件
const showNotCancelWarn = () => {
    return ElMessageBox.alert(
        `
        <p>
            <label style="color:#666666">您勾选的方案中包含无法取消的方案，请重新选择；</label><br/>
        </p>
         <div style="background: rgba(241, 90, 74, 0.05);border-radius: 4px;margin-top: 20px;padding: 16px;">
            <label style="color:#666666">可取消符合以下条件的方案：</label><br/>
            <ul>
                <li>1.草稿状态的方案；</li>
                <li>2.锁定点位状态的方案；</li>
                <li>3.确认投放状态，且还未到投放开始日期的方案；</li>
            </ul>
        </div>
    `,
        {
            confirmButtonText: '确定',
            showCancelButton: false,
            draggable: true,
            title: '提示',
            dangerouslyUseHTMLString: true,
        }
    ).then(
        () => true,
        () => false
    );
};

// 提示：恢复方案
// const showRecoverlWarn = () => {
//     return ElMessageBox.alert('存在同名方案，无法恢复', {
//         confirmButtonText: '确定',
//         showCancelButton: false,
//         type: 'warning',
//         draggable: true,
//         title: '提示',
//     }).then(
//         () => true,
//         () => false
//     );
// };

// 展示点位查询抽屉
const showSearchPoint = () => {
    showSearchPointDraw.value = true;
};

// 判断方案排斥是否展示
const isRepelStatus = (row: any) => {
    return row.planStatus === ProgramType.DRAFT || row.planStatus === ProgramType.LOCK;
};

// 展示方案排斥数据
const handleRepelList = (row: any) => {
    selectRow = Object.assign(selectRow, row);
    console.log('selectRow:', row);
    showRepelProjectDraw.value = true;
    console.log('handleRepelList', showRepelProjectDraw.value);
};
const selectedChange = (val: any) => {
    multipleSelection.value = val;
};

// 批量导出点位
const batchExportPoint = () => {
    if (!multipleSelection.value || !multipleSelection.value.length) {
        return showSelectWarn();
    }
    showBatchPointlDialog.value = true;
    console.log('batchExportPoint', showBatchPointlDialog.value);
    return false;
};
// 打开单个上传照片
const openPerUploadPhtDrawer = () => {
    showPerUploadPhtDraw.value = true;
    return false;
};
// todo  //没有弹窗 直接批量下载 服务器返回的 批量地址
const batchExportKanbaoPhoto = () => {
    console.log('batchExportKanbaoPhoto');
};

// todo  //没有弹窗 直接批量下载 服务器返回的 批量地址
const batchExportRealSKTable = () => {
    console.log('batchExportRealSKTable');
};

// 导出数字刊播报告

const showClipboard = ref({});
const exportKanbaoReport = async (row: any) => {
    const urldata = await exportKanBoReport({ userId: row.createMan, pid: row.planId });
    console.log('urldata', urldata);
    // if (!urldata.success) {
    //     ElMessage.error('资源生成错误');
    //     return;
    // }

    // 最好是服务端拼装完整地址 这里客户端拼装下
    const baseUrl = window.XCConfig.VITE_RES;
    const pathUrl = '/process/szkb-h5/#/verCode?ticket=' + urldata.ticket;
    const code = '提取码：' + urldata.code;

    showClipboard.value = {
        path: baseUrl + pathUrl,
        code,
    };

    const exportInfo = '新潮数字刊播报告链接:' + baseUrl + pathUrl + code;
    // 将信息复制到剪切板
    // copyTextToClipboard(encodeURI(baseUrl + pathUrl) + code);
    // copyTextToClipboard(exportInfo);
    writeDataToClipboard(exportInfo);
    console.log('数字报告：', exportInfo);
    showKanboReportlDialog.value = true;
    console.log('exportKanbaoReport');
};
// 导出数字刊播照片
const curOptPlanRow = ref({}); // 当前操作的行的数据
const exportKanbaoPhoto = (row: { id: string; beginTime: string }) => {
    curOptPlanRow.value = row;
    // 弹窗选择清晰度 上下刊
    showKanboPhotolDialog.value = true;
    console.log('exportKanbaoPhoto');
};

const viewPhoto = (row: any, imgaType: string) => {
    curOptPlanRow.value = row;
    console.log('viewPhoto');
    const imgType = imgaType;
    router.push({
        name: 'viewPhoto',
        query: {
            planId: row.planId,
            imgType,
            mediaType: formData.mediaType
        },
    });
};

// 导出实际上刊点位表
const exportRealSKTable = async (row: any) => {
    console.log('exportRealSKTable');
    console.log(row);

    const startTime = getDate(row.beginTime);
    const endTime = getDate(row.endTime);
    const planId = row.planId;
    const cityCode = row.city;

    const resUrl = await exportRealPointExcel({ startTime, endTime, planId, cityCode });

    exportFile(resUrl);
    console.log('resUrl', resUrl);
};

// 判断是否方案过期
const judgeOverdue = () => {
    const now = new Date();
    return !!multipleSelection.value.find((row: any) => {
        const putInPeriodArr = row.putInPeriod.split(' ~ ');
        console.log('putInPeriodArr', putInPeriodArr);
        const putInBegin = putInPeriodArr[0];
        return new Date(putInBegin) < now;
    });
};

// 判断方案来源是不是当前供应商的方案
const judgeCurrentProgram = () => {
    return !!multipleSelection.value.find((row: any) => {
        console.log(userInfo.value.channelCode, '--', row.planSource);
        return userInfo.value.channelCode !== row.planSource;
    });
};

// 判断是否可以取消
const judegeCancel = () => {
    // 已取消状态、过了投放日期的确认投放方案、方案来源不是当前供应商的方案，均无法取消
    return judgeCurrentProgram();
};

// 取消方案
const cancelPlanAction = async () => {
    tableLoading.value = true;
    const planId = multipleSelection.value.map((item: any) => item.planId).join(',');
    try {
        await cancelPlan(planId);
    } catch (e) {
        console.log('e', e);
    } finally {
        tableLoading.value = false;
        getList();
    }
};

// 提示：取消方案，二次确认
const showCancelWarn = () => {
    return ElMessageBox.alert(`您正在取消 <span style="color:#E60044">${multipleSelection.value.length}</span> 个方案，是否继续？`, {
        confirmButtonText: '确定',
        cancelButtonText: '再想想',
        showCancelButton: true,
        type: 'warning',
        draggable: true,
        title: '提示',
        dangerouslyUseHTMLString: true,
    }).then(
        () => cancelPlanAction(),
        () => false
    );
};

// 批量取消方案
const batchCancelPoint = () => {
    if (!multipleSelection.value || !multipleSelection.value.length) {
        return showSelectWarn();
    }
    if (judegeCancel()) {
        return showNotCancelWarn();
    }
    return showCancelWarn();
};
// 获取已取消方案
const getCancelListAction = async () => {
    getList();
};
// 恢复已取消方案
const handleRecover = async (row: any) => {
    tableLoading.value = true;
    try {
        await getRecoverList({ planId: row.planId });
    } catch (e) {
        console.log('e', e);
    } finally {
        tableLoading.value = false;
        getList();
    }
};
</script>

<style lang="scss" scoped>
// .common-table-tabs {
//     width: 100%;
//     :deep(.el-tabs__nav-wrap) {
//         overflow: initial;
//     }
// }
:deep(.el-table__body) {
    .xc-table-column {
        // background-color: pink;
        height: 52px !important;

        ._cell {
            padding-top: 0;
            padding-bottom: 0;
        }
    }
}

.el-tabs ::v-deep {
    .el-tabs__item {}
}

.el-dropdown {
    vertical-align: initial;

    .el-dropdown-link {
        cursor: pointer;
        color: var(--xc-button-text-color);
        display: flex;
        align-items: center;
    }
}

.el-table {

    .el-button + .el-button,
    .el-button + .el-dropdown,
    .el-dropdown + .el-button,
    .el-dropdown + .el-dropdown {
        margin-left: 20px;
    }
}

.btn-group {
    margin: 8px 0 15px;
}

.grayColor {
    color: #ccc;
}

.cancel-list {
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    .cancel-switch span {
        font-weight: 400;
        font-size: 14px;
        color: #666666;
        letter-spacing: 0;
        text-align: right;
        margin-right: 4px;
    }
}

.query-point {
    margin-right: 15px;
}

.create-btn {
    height: 8px;
    vertical-align: middle;
    margin-top: -1px;
}
</style>
